package com.my.jli.webapi;

import com.my.jli.Service.MyFileService;
import com.my.jli.Service.StudentService;
import com.my.jli.entity.MyFile;
import com.my.jli.entity.Student;
import com.my.jli.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @ClassName StudentRestController
 * @Description
 * @Author MaYu
 * @Date 2022/1/20 22:24
 * @Version 1.0
 **/
@RestController
@RequestMapping("/webapi/student")
public class StudentRestController {

    @Value("${file-save-path}")
    private String fileSavePath;

    //set方法注入service
    private StudentService studentService;
    @Autowired
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    private MyFileService myFileService;
    @Autowired
    public void setMyFileService(MyFileService myFileService) {
        this.myFileService = myFileService;
    }

    //获取所有学生
    @GetMapping("/list")
    public List<Student> getAll(){
        return studentService.getAll();
    }

    //通过id获取学生信息
    @GetMapping("/getById")
    public Student getById(Integer id){
        return studentService.getById(id);
    }

    //登录接口
    @GetMapping("/login")
    public int login(HttpSession session, String num, String pwd,
                     @RequestParam(value = "remember",defaultValue = "0") Integer remember,
                     HttpServletResponse response){

        List<Student> students = studentService.login(num, pwd);
        //如果匹配到一个学生
        if (students.size() == 1){
            //写入session
            session.setAttribute("student", students.get(0));
            if (remember == 1){
                CookieUtil.setCookie(response, "studentInfo", num + "@" + pwd, 60 * 60 * 24 * 7);
                System.out.println("生成cookie");
            }
            //登录成功， 返回1
            return 1;
        } else {
            //登录失败，返回-1
            return -1;
        }
    }

    /**
     * 分页查询
     * @param page 要查询的页数
     * @param size 一页的大小
     * @return 分页工具
     */
    @GetMapping("/getByPage")
    public PageUtil getByPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                              @RequestParam(value = "size", defaultValue = "5") Integer size,
                              Integer sex, String grade, String clazz, String num, String name, Integer tid){

        //ding定义排序方式
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Page<Student> studentPage;
        if ((name == null || name.equals("")) &&
                (num == null || num.equals("")) &&
                (sex == null) &&
                (grade == null || grade.equals("")) &&
                (clazz == null || clazz.equals(""))){
            //如果没有输入查询信息，则返回包含所有学生信息的分页信息
            Pageable pageable = PageRequest.of(page, size, sort);
            studentPage = studentService.getAll(tid, pageable);
        } else {

            Student student = new Student();
            student.setClazz(clazz);
            student.setGrade(grade);
            student.setName(name);
            student.setNum(num);
            student.setSex(sex);
            student.setTid(tid);

            //有查询信息则进行查询
            Pageable pageable = PageRequest.of(page, size, sort);
            //模糊查询
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("num", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("grade", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("clazz", ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Student> studentExample = Example.of(student, matcher);

            studentPage = studentService.getAll(studentExample, pageable);
        }

        PageUtil pageUtil = new PageUtil(studentPage.getContent(), studentPage.getTotalElements(), page);
        pageUtil.setTotalPage(size);

        return pageUtil;
    }

    @GetMapping("/getAllClazz")
    public Set<String> getAllClazz(){
        return studentService.getAllClazz();
    }

    @GetMapping("/getAllGrade")
    public Set<String> getAllGrade(){
        return studentService.getAllGrade();
    }

    /**
     * 添加学生信息
     * @param student 学生对象
     * @return 状态码 1为成功，0为学号被占用，-1为失败
     */
    @PostMapping("/saveStudent")
    public int saveStudent(Student student, @RequestParam(value = "isAdd", defaultValue = "true") boolean isAdd){
        //System.out.println("student = " + student);
        //先判断字段是否齐全
        if (!(StringUtils.hasText(student.getNum()) &&
                StringUtils.hasText((student.getPwd())) &&
                (student.getSex() == 0 || student.getSex() == 1) &&
                StringUtils.hasText(student.getName()) &&
                StringUtils.hasText(student.getGrade()) &&
                StringUtils.hasText(student.getClazz()) &&
                student.getTid() != null)){
            return -1;
        }

        if (isAdd){
            //查找此学生的学号是否重复
            Student student1 = studentService.getByNum(student.getNum());
            if (student1 == null){//没有匹配到学生，可以添加
                Student student2 = studentService.saveStudent(student);
                return student2 == null ? -1 : 1;
            } else {//数据库中已有此学生信息
                return 0;
            }
        } else {
            Student student1 = studentService.saveStudent(student);
            return student1 == null ? -1 : 1;
        }
    }

    /**
     * 通过文件（.xls .xlsx）批量添加学生
     * @param file 含有学生信息的excel文件
     * @param tid 教师id
     * @return 成功添加的条数，-1为失败
     */
    @PostMapping("/addStudentByFile")
    public int addStudentByFile(MultipartFile file, Integer tid){
        //记录成功添加的学生信息条数
        int count = 0;
        if (file != null && file.getSize() > 0){//文件不为空
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀
            String[] filename = originalFilename.split("\\.");
            //创建临时文件
            try {
                File tempFile = File.createTempFile(filename[0], "." + filename[1]);
                file.transferTo(tempFile);
                List<Student> studentList = ExcelUtil.getStudentList(tempFile, tid);
                //System.out.println(studentList);
                //System.out.println("tempFile = " + tempFile);
                //开始添加
                if (studentList != null){
                    for (Student student : studentList) {
                        //先判断字段是否齐全
                        if (!(StringUtils.hasText(student.getNum()) &&
                                StringUtils.hasText((student.getPwd())) &&
                                (student.getSex() == 0 || student.getSex() == 1) &&
                                StringUtils.hasText(student.getName()) &&
                                StringUtils.hasText(student.getGrade()) &&
                                StringUtils.hasText(student.getClazz()) &&
                                student.getTid() != null)){
                            return -1;
                        }
                        //查找此学生的学号是否重复
                        Student student1 = studentService.getByNum(student.getNum());
                        if (student1 == null){//没有匹配到学生，可以添加
                            Student student2 = studentService.saveStudent(student);
                            //成功添加则计数+1，否则不变
                            count = student2 == null ? count : count + 1;
                        }
                    }
                }
                //业务完成删除临时文件
                tempFile.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return count;
        } else {
            return -1;
        }
    }

    /**
     * 根据id删除学生信息
     * @param id 学生id
     * @return 状态码 1为成功，-1为失败
     */
    @DeleteMapping("/deleteById")
    public int deleteById(Integer id){
        Student student = studentService.getById(id);
        if (student == null){
            return -1;
        } else {
            studentService.deleteById(id);
            return 1;
        }
    }

    /**
     * 学生进行签到
     * @param session session
     * @param code 签到码
     * @return 完成状态代码，1=成功，2=未发布签到，-1=失败
     */
    @RequestMapping("/sign")
    public int sign(HttpSession session, String code){
        SignCodeUtil signCodeUtil = (SignCodeUtil) session.getAttribute("signCodeUtil");

        if (signCodeUtil == null){
            //未发布签到
            return 2;
        }

        long remainingTime = signCodeUtil.getEndDate() - new Date().getTime();
        System.out.println("签到码剩余生效时间：" + remainingTime / 1000 + "s");

        if (remainingTime > 0 && signCodeUtil.getCode().equals(code)){
            //获取已签到的学生set集合
            Set<Student> signStu = signCodeUtil.getSignStu();
            //从session中获取学生对象
            Student student = (Student) session.getAttribute("student");

            signStu.add(student);
            signCodeUtil.setSignStu(signStu);
            signStu.add(student);
            signCodeUtil.setSignStu(signStu);

            session.setAttribute("signCodeUtil", signCodeUtil);
            return 1;
        } else {
            return -1;
        }
    }


    /**
     * 学习文件上传
     * @param file 传入的文件对象
     * @return 状态码，1=成功，-1=失败
     */
    @RequestMapping("/upload")
    public int uploadFile(MultipartFile file){
        if (file != null && file.getSize() > 0){
            //重命名文件
            String filename = file.getOriginalFilename();
            String fileNameNew = FileUtil.getFileNameNew(filename);
            //生成动态文件夹
            String datePath = FileUtil.getDatePath();
            String filePath = fileSavePath + "/" + datePath;
            File file1 = new File(filePath);
            if (!file1.exists()){
                //如果路径不存在则新建
                boolean b = file1.mkdirs();
                if (!b){
                    //如果文件路径创建失败返回-1
                    return -1;
                }
            }
            File file2 = new File(filePath + "/" + fileNameNew);
            System.out.println(file2.getPath());
            try {
                file.transferTo(file2);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //设置文件信息
            MyFile myFile = new MyFile();
            myFile.setFilename(filename);
            //设置路径
            myFile.setFilepath(datePath + "/" + fileNameNew);
            myFile.setSize(file.getSize());
            myFile.setUpdateDate(new Date());
            assert filename != null;
            myFile.setType(filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(Locale.ROOT));
            myFile.setJurisdiction(0);

            //存入数据库
            myFileService.addMyFile(myFile);
            return 1;
        } else {
            return -1;
        }
    }

    /**
     * 修改学生密码
     * @param id 学生id
     * @param newPwd 新密码
     * @return 状态码 -1=失败 1=成功
     */
    @PostMapping("/changePwd")
    public int changePwd(Integer id, String newPwd){
        Student student = studentService.getById(id);
        //新密码为空返回失败
        if (newPwd == null || newPwd.equals("")){
            return -1;
        }
        //新密码和旧密码相同返回失败
        if (student.getPwd().equals(newPwd)){
            return -1;
        } else {
            student.setPwd(newPwd);
            studentService.update(student);
            return 1;
        }
    }
}
